package com.jwm.power.util;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Auther: chenjinbo
 * @Date: 2019/5/16 09:05
 * @Description: 文件上传工具类
 */
@Component
public class FileUtil {


//    @Value("${file.uploadJwmAppPath}")

    @Value("${file.uploadPath}")
    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    private static String uploadPath;

    public static FileUtil fileUtil;

    //实现从外部调用service
    @PostConstruct
    public void init() {
        fileUtil = this;
    }

    private static String staticAccessPath = "/uploadfiles/";

    public static String getStaticAccessPath() {
        return staticAccessPath;
    }

    public static String getServerPath() {
        try {
            String serverPath = URLDecoder.decode(ResourceUtils.getURL("").getPath(), "UTF-8");
            return serverPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传文件
     *
     * @param file
     * @param flag 0-使用原文件名，1-使用新文件名
     * @param water 0-不使用水印，1-使用水印
     */
    public static String uploadFiles(MultipartFile file, int flag ,Integer water) {
        String filename = "";
        String datePath = "";
        try {
            // 上传文件
            // 获取原始文件名
            String fileName = file.getOriginalFilename();
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            // 新文件名
            String newFileName = UUID.randomUUID().toString() + suffixName;

            if (flag == 0) {
                newFileName = fileName;
            }
            // 设置并上传附件
            //File dest = new File(getServerPath() + uploadPath + newFileName);
            //获取日期
            Date nowDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            datePath = sdf.format(nowDate) + "/";
            File dest = new File(getServerPath() + uploadPath + datePath + newFileName);
            // 检测是否存在目录，不存在创建
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            if( water == 1){
                Image img = ImageIO.read(dest);
                int width = img.getWidth(null);
                int height = img.getHeight(null);
                BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bi.createGraphics();
                g.drawImage(img, 0, 0, width, height, null);
                //设置字体大小、颜色等
                g.setColor(Color.RED);
                g.setFont(new Font("微软雅黑", Font.BOLD + Font.ITALIC, 60));
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date day = new Date();
                String strFont = df.format(day);
                g.drawString(strFont, 30, height-30);
                g.dispose();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                String fileTyle=fileName.substring(fileName.lastIndexOf("."),fileName.length());
                ImageIO.write(bi, fileTyle, out);
                OutputStream os = null;
                os = new FileOutputStream(uploadPath + datePath + newFileName);
                //创建图像编码工具类
                JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
                //使用图像编码工具类，输出缓存图像到目标文件
                en.encode(bi);
                if (os != null) {
                    os.close();
                }
            }

            filename += newFileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/upload/" + datePath + filename;
    }


    /**
     * 上传文件
     *
     * @param files
     * @param flag  0-使用原文件名，1-使用新文件名
     */
    public static String uploadFiles(MultipartFile[] files, int flag) {
        String filename = "";
        try {
            // 上传文件
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                // 获取原始文件名
                String fileName = file.getOriginalFilename();
                // 获取文件的后缀名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                // 新文件名
                String newFileName = UUID.randomUUID().toString() + suffixName;

                if (flag == 0) {
                    newFileName = fileName;
                }
                // 设置并上传附件
                File dest = new File(getServerPath() + uploadPath + newFileName);
                // 检测是否存在目录，不存在创建
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                file.transferTo(dest);

                //将.aac文件转为.mp3文件
                if (newFileName.toLowerCase().contains(".aac") || newFileName.toLowerCase().contains(".mp3")) {
                    String tempFileName = newFileName.substring(0, fileName.lastIndexOf("."));
                    String inFilePath = uploadPath + newFileName;
                    String outFilePath = uploadPath + tempFileName + ".mp3";
                    if (convertMP3(inFilePath, outFilePath)) {
                        // 删除原文件
                        if (inFilePath.toLowerCase().contains(".acc")) {
                            File aacFile = new File(inFilePath);
                            if (aacFile.exists() && aacFile.isFile()) {
                                aacFile.delete();
                            }
                            newFileName = tempFileName + ".mp3";
                        }
                    }
                }
                //将.mov文件转为.mp4文件
                if (newFileName.toLowerCase().contains(".mov")) {
                    String tempFileName = newFileName.substring(0, fileName.lastIndexOf(".mov"));
                    String inFilePath = uploadPath + tempFileName + ".mov";
                    String outFilePath = uploadPath + tempFileName + ".mp4";
                    if (convertMP3(inFilePath, outFilePath)) {
                        File aacFile = new File(inFilePath);
                        if (aacFile.exists() && aacFile.isFile()) {
                            aacFile.delete();
                        }
                        newFileName = tempFileName + ".mp4";
                    }
                }

                if (i == 0) {
                    filename += newFileName;
                } else {
                    filename += "@" + newFileName;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filename;
    }

    /**
     * 将本地aac音频文件转换成mp3格式文件
     *
     * @param inFile  本地aac文件物理路径
     * @param outFile 转换后mp3文件的物理路径
     */
    public static Boolean convertMP3(String inFile, String outFile) throws IOException, java.lang.InterruptedException {
        String ffmpegPath = URLDecoder.decode(ResourceUtils.getURL("classpath:").getPath() + "static/Mov2Mp4/ffmpeg.exe", "UTF-8");
        String convertMedia = ffmpegPath + " -i " + inFile + " -ab 128 -acodec libmp3lame -ac 1 -ar 22050 -r 29.97 -qscale 6 -y " + outFile;
        if (inFile.toLowerCase().contains(".mov")) {
            convertMedia = ffmpegPath + " -loglevel quiet -y -i " + inFile + " -vcodec h264 " + outFile;
        } else if (inFile.toLowerCase().contains(".aac") || inFile.toLowerCase().contains(".mp3")) {
            convertMedia = ffmpegPath + " -loglevel quiet -i " + inFile + " -ab 128 -acodec libmp3lame -ac 1 -ar 22050 -r 29.97 -qscale 6 -y " + outFile;
        }

        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(convertMedia);
        InputStream stderr = proc.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stderr);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                System.out.println("doing...");
            }
            int exitVal = proc.waitFor();
            br.close();
            isr.close();
            stderr.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (br != null) br.close();
            if (isr != null) isr.close();
            if (stderr != null) stderr.close();
        }
    }

    /**
     * 获取图片列表
     *
     * @param imgname
     * @return
     */
    public static List<String> getImglist(String imgname) {
        List<String> imglist = new ArrayList<String>();
        String[] arr = imgname.split("@");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].toLowerCase().contains(".png") || arr[i].toLowerCase().contains(".jpg") || arr[i].toLowerCase().contains(".jpeg")) {
                imglist.add(staticAccessPath + arr[i]);
            }
        }
        return imglist;
    }

    /**
     * 获取视频列表
     *
     * @param imgname
     * @return
     */
    public static List<String> getVideolist(String imgname) {
        List<String> imglist = new ArrayList<String>();
        String[] arr = imgname.split("@");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].toLowerCase().contains(".mp4")) {
                imglist.add(staticAccessPath + arr[i]);
            }
        }
        return imglist;
    }

    /**
     * 获取音频列表
     *
     * @param imgname
     * @return
     */
    public static List<String> getAudiolist(String imgname) {
        List<String> imglist = new ArrayList<String>();
        String[] arr = imgname.split("@");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].toLowerCase().contains(".mp3")) {
                imglist.add(staticAccessPath + arr[i]);
            }
        }
        return imglist;
    }

}
